package com.itheima.task;

import com.itheima.common.constant.RedisConstant;
import com.itheima.common.utils.AliOssUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @className ImageCleanupTask
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class ImageCleanupTask {

    private final AliOssUtil aliOssUtil;
    private final RedisTemplate<String, String> redisTemplate;

    /**
     * 定时任务：清理多余图片，每天凌晨3点执行
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void cleanupExcessImages() {
        log.info("开始执行图片清理任务...");
        // 计算redis中库中的图片名和已上传的图片名之间的差集
        Objects.requireNonNull(redisTemplate.opsForSet().difference(RedisConstant.DB_IMAGES_KEY, RedisConstant.UPLOADED_IMAGES_KEY))
                .forEach(fileName -> {
                    try {
                        log.info("需要删除的图片:{}", fileName);
                        // 删除AliOSS中多余的文件
                        aliOssUtil.delete(fileName);
                        // 删除Redis中已上传的图片文件名
                        redisTemplate.opsForSet().remove(RedisConstant.UPLOADED_IMAGES_KEY, fileName);
                    } catch (Exception e) {
                        log.error("删除图片失败:{}，失败原因:{}",fileName, e);
                    }
                });
    }
}
